;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Sales.Allocation", [])
        .controller("AllocationCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "UserContextService", "Upload", "$timeout", "EventBus", "$filter", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, UserContextService, Upload, $timeout, EventBus, $filter) {
            $scope.activeFlag = [true, false, false, false];
            $scope.detailFlag = [true, true];
            $scope.datePickerFlag = [false, false];
            $scope.markInfo = {
                allCheckedBill: false,
                allCheckedMaterial: false,
                curRow: -1
            };
            $scope.showDatepicker = false;
            $scope.submitted = false;
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.condition = {};
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
                showMateriel: false
            };
            $scope.dataList = [];
            $scope.detailInfo = {
                crucialDevice: 0,
                entranceDevice: 0
            };
            $scope.tabFlag = {};
            var tabFlag = {
                0: "客户调拨详情",
                1: "新增客户调拨",
                2: "编辑客户调拨"
            };
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/agentAllot/export"),
                sectionParam: {ids: []},
                allUrl: ybHttp.RequestUrl("device", "/agentAllot/exportAll")
            };
            $scope.orderObj = {
                headerInfo: {},
                detailList: []
            };
            $scope.stateList = [
                {code: 0, name: '未完成'},
                {code: 1, name: '部分完成'},
                {code: 2, name: '已完成'}
            ];
            $scope.billStatus = [
                {code: 0, name: '草稿'},
                {code: 1, name: '未完成'},
                {code: 2, name: '调出通过'},
                {code: 3, name: '调出驳回'},
                {code: 4, name: '调入通过'},
                {code: 5, name: '调入驳回'}
            ];
            $scope.tableConfig = {
                fixedWidth: 270,
                scrollWidth: 1560,
                tableCol: [
                    {
                        type: "",
                        name: "调拨单号",
                        dataField: "allotOrder",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调拨角色",
                        dataField: "roleTypeShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调出客户",
                        dataField: "outAgentName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调出状态",
                        dataField: "outStateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调入客户",
                        dataField: "inAgentName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调入状态",
                        dataField: "inStateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "发货日期",
                        dataField: "deliveryDateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "createDateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单部门",
                        dataField: "deptName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "状态",
                        dataField: "verifyStateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核意见",
                        dataField: "note",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        name: "入库时间",
                        dataField: "inDateShow",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "出库时间",
                        dataField: "outDateShow",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 230,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.materielTableConfig = {
                scrollWidth: 900,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        needInput: false
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        needInput: false
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        needInput: false
                    },
                    {
                        name: "申请数量",
                        width: 100,
                        dataField: "amount",
                        needInput: true
                    },
                    {
                        name: "单价",
                        width: 100,
                        dataField: "price",
                        needInput: true
                    },
                    {
                        name: "小计",
                        width: 100,
                        dataField: "totalPrice",
                        needInput: false
                    },
                    {
                        name: "成本单价",
                        width: 100,
                        dataField: "costPrice",
                        type: "cost",
                        needInput: false
                    },
                    {
                        name: "成本小计",
                        width: 100,
                        dataField: "costSubtotal",
                        type: "cost",
                        needInput: false
                    }
                ]
            };
            $scope.inTbConf = {
                scrollWidth: 1100,
                tableCol:
                    [
                        {
                            name: "零件编号",
                            width: 150,
                            dataField: "materialsNo",
                            needInput: false
                        },
                        {
                            name: "零件中文名",
                            width: 200,
                            dataField: "materialsDes",
                            needInput: false
                        },
                        {
                            name: "单位",
                            width: 100,
                            dataField: "unit",
                            needInput: false
                        },
                        {
                            name: "申请数量",
                            width: 120,
                            dataField: "amount",
                            needInput: true,
                            needRequired: true
                        },
                        {
                            name: "调出完成数",
                            width: 120,
                            dataField: "outAmount",
                            needInput: false
                        },
                        {
                            name: "调入完成数",
                            width: 120,
                            dataField: "inAmount",
                            needInput: false
                        },
                        {
                            name: "储位",
                            width: 150,
                            dataField: "locationCode",
                            input: true,
                            inputType: "func"
                        },
                        {
                            name: "备注",
                            width: 300,
                            dataField: "remark",
                            needInput: true,
                            needRequired: false
                        }
                    ]
            };
            $scope.costPriceShow = false;

            var btnPermissionCode = {
                clientAllocationAdd: window.ActionCode.clientAllocationAdd,
                clientAllocationEdit: window.ActionCode.clientAllocationEdit,
                clientAllocationDel: window.ActionCode.clientAllocationDel,
                clientAllocationAudit: window.ActionCode.clientAllocationAudit,
                clientAllocationPrint: window.ActionCode.clientAllocationPrint,
                clientAllocationExport: window.ActionCode.clientAllocationExport,
                clientAllocationIn: window.ActionCode.clientAllocationIn,
                clientAllocationOut: window.ActionCode.clientAllocationOut,
                showCostPrice: window.ActionCode.showCostPrice,
                clientAllocationSettle:window.ActionCode.clientAllocationSettle
            };

            $scope.btnPermission = {
                clientAllocationAdd: true,
                clientAllocationEdit: true,
                clientAllocationDel: true,
                clientAllocationAudit: true,
                clientAllocationPrint: true,
                clientAllocationExport: true,
                clientAllocationIn: true,
                clientAllocationOut: true,
                showCostPrice: true,
                clientAllocationSettle:true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {left: $scope.tableConfig.fixedWidth + "px"}
                };
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        getDataList();
                        $scope.submitted = false;
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    default:
                        break;
                }
            };

            function initData() {
                $scope.tabFlag = {};
                $scope.detailInfo = {
                    crucialDevice: 0,
                    entranceDevice: 0
                };
                $scope.orderObj = {
                    headerInfo: {},
                    detailList: []
                };
                $scope.markInfo.allCheckedMaterial = false;
                $scope.toolbarConfig.showMateriel = false;
                $scope.detailFlag = [true, true];
            }

            function getDataList(curPage) {
                $scope.markInfo = {
                    allCheckedBill: false,
                    allCheckedMaterial: false,
                    curRow: -1
                };
                $scope.exportParam.sectionParam.ids = [];
                var service = "device";
                var reqUrl = "/agentAllot/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = $scope.condition;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createDateShow = $filter("YbDate")(item.createDate, "yyyy-MM-dd HH:mm:ss");
                        item.deliveryDateShow = $filter("YbDate")(item.deliveryDate, "yyyy-MM-dd HH:mm:ss");
                        item.roleTypeShow = $filter("allocationRole")(item.roleType);
                        item.verifyStateShow = $filter("ProgressStatus")(item.verifyState, "verifyState");
                        item.outStateShow = $filter("allotState")(item.outState);
                        item.inStateShow = $filter("allotState")(item.inState);
                        item.inDateShow = $filter("YbDate")(item.inDate, "yyyy-MM-dd HH:mm:ss");
                        item.outDateShow = $filter("YbDate")(item.outDate, "yyyy-MM-dd HH:mm:ss");
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }


            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };
            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };


            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    default:
                        break;
                }
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {};
            };

            $scope.switchDetailBar = function (index) {
                $scope.detailFlag[index] = !$scope.detailFlag[index];
            };

            $scope.delMateriel = function (item, index, e) {
                ybWidget.ShowMessage("确定要删除该记录吗？", MESG_TYPE.Ask).then(function () {
                    $scope.orderObj.detailList.splice(index, 1);
                    EventBus.Publish("setMaterial", item.materialsNo);
                    e.stopPropagation();
                });
            };

            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = 0, len = $scope.orderObj.detailList.length; i < len; i++) {
                    if (!!$scope.orderObj.detailList[i].isChecked) {
                        selectedCount++;
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    for (var i = $scope.orderObj.detailList.length - 1; i >= 0; i--) {
                        if (!!$scope.orderObj.detailList[i].isChecked) {
                            $scope.orderObj.detailList.splice(i, 1);
                        }
                    }
                    if ($scope.orderObj.detailList.length === 0) {
                        $scope.markInfo.allCheckedMaterial = false;
                    }
                    EventBus.Publish("setMaterial");
                });
            };

            $scope.delApply = function (item) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    var reqUrl = "/agentAllot/remove";
                    var param = {
                        ids: []
                    };
                    param.ids.push(item.id);
                    ybHttp.Post(service, reqUrl, param.ids).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                })
            };

            $scope.addApply = function () {
                $scope.tabFlag.type = 1;
                $scope.tabFlag.name = tabFlag[1];
                $scope.orderObj.headerInfo.createDate = +new Date();
                $scope.orderObj.headerInfo.createName = $scope.curUser.name;
                $scope.orderObj.headerInfo.deptId = $scope.curUser.deptId;
                $scope.orderObj.headerInfo.deptName = $scope.curUser.deptName;
                $scope.changeTab(2);
            };

            function getDetail(item, type) {
                var param = {
                    id: item.id
                };
                return ybHttp.Get('device', '/agentAllot/item', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.detailList, function (item) {
                        item.materialsDes = item.materialName;
                        item.materialsNo = item.materialNo;
                        item.price = item.refPrice;
                    });
                    if (!!resp.value.headerInfo.deliveryDate) {
                        resp.value.headerInfo.deliveryDate = new Date(resp.value.headerInfo.deliveryDate);
                    }
                    return resp.value;
                });
            }

            $scope.editApply = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.orderObj = data;
                    $scope.tabFlag.name = tabFlag[2];
                    $scope.tabFlag.type = 2;
                    $scope.changeTab(2);
                });
            };

            function viewDetail(item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.orderObj = data;
                    $scope.changeTab(3);
                });
            }

            $scope.auditApply = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.orderObj = data;
                    $scope.changeTab(1);
                });
            };

            $scope.selMateriel = function (e) {
                if (!!$scope.toolbarConfig.showMateriel) {
                    e.stopPropagation();
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig.showMateriel = true;
                        EventBus.Publish("getMaterial");
                    });
                }
            };

            $scope.importMateriel = function () {
                if (!$scope.orderObj.headerInfo.outAgentId) {
                    ybWidget.ShowToaster('error', '请选择调出客户');
                    return;
                }
                var param = {
                    name: "零件",
                    templateReqService: "device",
                    templateReqUrl: "/agentAllot/download",
                    importReqService: "device",
                    importReqUrl: "/agentAllot/import",
                    importErrorUrl: "",
                    orgId: $scope.orderObj.headerInfo.outAgentId
                };
                ybWidget.ImportFile(param).then(function (data) {
                    angular.forEach(data, function (item) {
                        item.isChecked = false;
                    });
                    $scope.orderObj.detailList = [];
                    $scope.orderObj.detailList = angular.copy(data);
                });
            };

            // 出库
            $scope.goOutbound = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.tabFlag.type = 3;
                    $scope.orderObj = data;
                    $scope.changeTab(5);
                });
            };

            // 入库
            $scope.goInbound = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    // 入库时把入库的默认储位赋值给locationCode字段
                    /*angular.forEach(data.detailList, function (item) {
                        item.locationCode = item.inLocationCode;
                    });*/
                    $scope.orderObj = data;
                    $scope.tabFlag.type = 4;
                    $scope.changeTab(4);
                });
            };

            $scope.inboundSubmit = function () {
                if (!$scope.orderObj.headerInfo.warehouseCode) {
                    ybWidget.ShowMessage('请先选择仓库', MESG_TYPE.Error);
                    return;
                }
                var service = "device";
                var reqUrl = "/warehouseInboundRecord/receive";
                var param = {
                    headerInfo: {},
                    detailList: []
                };
                var errorCount = 0;
                param.headerInfo.businessOrder = $scope.orderObj.headerInfo.allotOrder;
                angular.forEach($scope.orderObj.detailList, function (item) {
                    var listRow = {};
                    listRow.materialNo = item.materialNo;
                    listRow.locationCode = item.locationCode;
                    item.locationErr = false;
                    if (!item.locationCode) {
                        item.locationErr = true;
                        errorCount++;
                    }
                    param.detailList.push(listRow);
                });
                if (errorCount > 0) {
                    return;
                }

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };

            $scope.outboundSubmit = function () {
                if (!$scope.orderObj.headerInfo.warehouseCode) {
                    ybWidget.ShowMessage('请先选择仓库', MESG_TYPE.Error);
                    return;
                }

                var service = "device";
                var reqUrl = "/warehouseDeliveryRecord/receive";
                var param = {
                    headerInfo: {},
                    detailList: []
                };
                var errorCount = 0;
                param.headerInfo.businessOrder = $scope.orderObj.headerInfo.allotOrder;
                angular.forEach($scope.orderObj.detailList, function (item) {
                    var listRow = {};
                    listRow.materialNo = item.materialNo;
                    listRow.locationCode = item.locationCode;
                    item.locationErr = false;
                    if (!item.locationCode) {
                        item.locationErr = true;
                        errorCount++;
                    }
                    param.detailList.push(listRow);
                });
                if (errorCount > 0) {
                    return;
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };

            $scope.selDepot = function (item) {
                if(!$scope.orderObj.headerInfo.warehouseCode){
                    ybWidget.ShowMessage('请先选择仓库', MESG_TYPE.Error);
                    return;
                }
                var param = {
                    warehouseCode: $scope.orderObj.headerInfo.warehouseCode
                };

                ybWidget.DepotSelector(param).then(function (data) {
                    item.warehouseCode = data.warehouseCode;
                    item.areaCode = data.areaCode;
                    item.locationCode = data.locationCode;
                })
            };

            $scope.clearDepot = function (item) {
                item.warehouseCode = "";
                item.areaCode = "";
                item.locationCode = "";
            };
            // 选择仓库
            $scope.selectWarehouse = function () {
                ybWidget.WarehouseSelector().then(function (data) {
                    $scope.orderObj.headerInfo.warehouseCode = data.warehouseCode;
                })
            };

            // 入库时清除仓库
            $scope.clearWarehouse = function () {
                $scope.orderObj.headerInfo.warehouseCode = null;
            };

            $scope.checkQty = function (item) {
                item.qtyErr = false;
                if (!item.amount || item.amount == "0") {
                    item.qtyErr = true;
                }else{
                    // 设置价格小计
                    item.totalPrice = $filter("decimalCover")(ybWidget.Times(item.price, item.amount), 2);
                    // 设置成本小计
                    item.costSubtotal = $filter("decimalCover")(ybWidget.Times(item.costPrice, item.amount), 2);
                }
                setTotal();
            };

            // 设置总价
            function setTotal () {
                var costTotal = 0;
                angular.forEach($scope.orderObj.detailList, function (item) {
                    // 成本总价
                    costTotal = $filter("decimalCover")(ybWidget.Plus(costTotal, item.costSubtotal), 2);
                });
                $scope.orderObj.headerInfo.costTotal = costTotal;
            }

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.saveData = function (type, invalid) {
                if (!invalid) {
                    $scope.submitted = true;
                    return;
                }
                var listValid = true;
                var service = "device";
                var reqUrl = "/agentAllot/add";
                if (type === "submit") {
                    reqUrl = "/agentAllot/submit";
                }
                if (!$scope.orderObj.detailList || $scope.orderObj.detailList.length == 0) {
                    ybWidget.ShowToaster('error', '零件不可为空');
                    return;
                }
                // if (!!$scope.orderObj.headerInfo.allotOrder) {
                //     reqUrl = "/agentAllot/update";
                // }
                for (var i = 0, len = $scope.orderObj.detailList.length; i < len; i++) {
                    $scope.orderObj.detailList[i].qtyErr = false;
                    $scope.orderObj.detailList[i].materialName = $scope.orderObj.detailList[i].materialsDes;
                    $scope.orderObj.detailList[i].materialNo = $scope.orderObj.detailList[i].materialsNo;

                    if (angular.isUndefined($scope.orderObj.detailList[i].amount) || !$scope.orderObj.detailList[i].amount || $scope.orderObj.detailList[i].amount == "0") {
                        $scope.orderObj.detailList[i].qtyErr = true;
                        listValid = false;
                        break;
                    }
                }
                if (!listValid) {
                    return;
                }

                angular.forEach($scope.orderObj.detailList, function (item) {
                    item.refPrice = item.price;
                });

                var param = angular.copy($scope.orderObj);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
            };

            $scope.auditPurchase = function (type, headerInfo, message) {
                var service = "device";
                var reqUrl = "/agentAllot/updateState";
                var param = {
                    id: headerInfo.id,
                    note: message,
                    verifyState: 0

                };
                if (type === "refuse" && !message) {
                    ybWidget.ShowMessage('请输入审核意见');
                    $scope.submitted = true;
                    return;
                }
                if (type === "pass" && headerInfo.roleType === 1) {
                    param.verifyState = 2;
                }
                if (type === "refuse" && headerInfo.roleType === 1) {
                    param.verifyState = 3;
                }
                if (type === "pass" && headerInfo.roleType === 2) {
                    param.verifyState = 4;
                }
                if (type === "refuse" && headerInfo.roleType === 2) {
                    param.verifyState = 5;
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    $scope.orderObj.headerInfo.note = "";
                });
            };

            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            $scope.selectAgent = function (type, selectedId) {
                ybWidget.AgentSelector(selectedId).then(function (data) {
                    if (type == 'in') {
                        $scope.orderObj.headerInfo.inAgentId = data.platOrgId;
                        $scope.orderObj.headerInfo.inAgentName = data.companyName;
                        $scope.orderObj.headerInfo.inAgentContact = data.contact;
                        $scope.orderObj.headerInfo.inAgentPhone = data.contactTel;
                    }
                    if (type == 'out') {
                        if (!!$scope.orderObj.headerInfo.outAgentId && (data.platOrgId !== $scope.orderObj.headerInfo.outAgentId)) {
                            clearMateriel();
                        }
                        $scope.orderObj.headerInfo.outAgentId = data.platOrgId;
                        $scope.orderObj.headerInfo.outAgentName = data.companyName;
                        $scope.orderObj.headerInfo.outAgentContact = data.contact;
                        $scope.orderObj.headerInfo.outAgentPhone = data.contactTel;
                    }
                })
            };

            $scope.clearAgent = function (type) {
                if (type == 'in') {
                    $scope.orderObj.headerInfo.inAgentId = "";
                    $scope.orderObj.headerInfo.inAgentName = "";
                    $scope.orderObj.headerInfo.inAgentContact = "";
                    $scope.orderObj.headerInfo.inAgentPhone = "";
                }
                if (type == 'out') {
                    $scope.orderObj.headerInfo.outAgentId = "";
                    $scope.orderObj.headerInfo.outAgentName = "";
                    $scope.orderObj.headerInfo.outAgentContact = "";
                    $scope.orderObj.headerInfo.outAgentPhone = "";
                    clearMateriel();
                }
            };

            $scope.selectPerson = function() {
                ybWidget.DataSelector({
                    title: '联系人',
                    url: '/employee/list',
                    keyWords: [{label: '网点名称', field: 'cnameLike'}],
                    fields: [
                        {
                            name: '联系人',
                            dataField: 'cname',
                            width: "30%"
                        },
                        {
                            name: '联系方式',
                            dataField: 'contactTel',
                            width: "30%"
                        },
                        {
                            name: '联系地址',
                            dataField: 'address',
                            width: "40%"
                        }
                    ]
                }).then(function (data) {
                    $scope.orderObj.headerInfo.inAgentContact = data.cname;
                    $scope.orderObj.headerInfo.inAgentPhone = data.contactTel;
                    $scope.orderObj.headerInfo.inAddress = data.address;
                })
            };

            function clearMateriel() {
                $scope.orderObj.detailList = [];
                $scope.markInfo.allCheckedMaterial = false;
                $timeout(function () {
                    if (!$scope.orderObj.headerInfo.outAgentId) {
                        EventBus.Publish("clearMaterial");
                    } else {
                        EventBus.Publish("getMaterial");
                    }
                });
            }

            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
                getBillIds();
            };

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                getBillIds();
            };

            $scope.settlement = function (item) {
                ybWidget.ShowConfirm('确定要对该记录结算吗？', '备注', { required: false }).then(function(data) {
                    var service = "device";
                    var reqUrl = "/agentAllot/settle";
                    var param = {
                        id: item.id,
                        remark: !!data ? data: ''
                    };
                    ybHttp.Get(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    })
                })
            };

            $scope.printBill = function (item) {
                var id = item.id;
                var billIds = [];
                billIds.push(id);
                var param = {
                    billId: billIds,
                    printType: "Allocation"
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            (function () {
                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }])
    ;
})(window, window.angular);
